<script setup>
import {onMounted, ref} from "vue";
import {
  deleteChapters, deleteSections,
  //标注 deleteChapters 在 post.js 中还未实现
  getAllChapters,
  getAllSections,
  getCourses
} from "@/api/post.js";
import {useRoute} from "vue-router";


const chapters = ref([]);
const sections = ref([]);

// 本地展开状态管理
const expandedChapters = ref(new Set());
const expandedSections = ref(new Set());

// 获取课程、章节和小节数据
function fetchData() {
  getAllChapters()
    .then((res) => {
      chapters.value = res.data.chapters;
    })
    .catch((e) => console.error("Failed to fetch chapters:", e));

  getAllSections()
    .then((res) => {
      sections.value = res.data.sections;
    })
    .catch((e) => console.error("Failed to fetch sections:", e));
}

// 组件加载成功后调用 fetchData
onMounted(() => {
  fetchData();
});

const route = useRoute()
const courseId = parseInt(route.params.id)
console.log(courseId.type)
const form = ref({
  id: '',
  title: '',
  description: ''
})

const getChaptersByCourseId = (courseId) => {
  return chapters.value.filter((chapter) => chapter.courseId === courseId);
};
const getSectionsByChapterId = (chapterId) => {
  return sections.value.filter((section) => section.chapterId === chapterId);
};

const toggleChapter = (chapterId) => {
  expandedChapters.value.has(chapterId)
    ? expandedChapters.value.delete(chapterId)
    : expandedChapters.value.add(chapterId);
};

const toggleSection = (sectionId) => {
  expandedSections.value.has(sectionId)
    ? expandedSections.value.delete(sectionId)
    : expandedSections.value.add(sectionId);
};

function confirmDelete(id){
  if (window.confirm("确定删除？")) {
    deleteChapters(id)
      .then(() => {
        this.chapters = this.chapters.filter(chapter => chapter.chapterId !== id);
      })
      .catch(error => {
        console.error('Error deleting chapter:', error);
      });
  }
}
function Delete(id){
  if (window.confirm("确定删除？")) {
    deleteSections(id)
      .then(() => {
        this.sections = this.sections.filter(section => section.sectionId !== id);
      })
      .catch(error => {
        console.error('Error deleting section:', error);
      });
  }
}

onMounted(() => {
  fetchData();
});
// 获取课程详情
onMounted(async () => {
  try {
    const res = await getCourses()
    const course = res.data.courses.find(c => c.courseId == courseId)
    if (course) {
      form.value = {
        id: course.courseId,
        title: course.title,
        description: course.description || ''
      }
    }
  } catch (e) {
    console.error('获取课程详情失败:', e)
  }
})
</script>

<template>
    <div>
        <h1>课程详情</h1>
        <div class="card">
          <div style="max-width: 600px;">
            <div style="margin-bottom: 20px;">
            <label style="display: block; margin-bottom: 8px;">课程标题：</label>
            <el-input disabled v-model="form.title" />
            </div>
            <div style="display: flex; align-items: center;">
              <label style="flex-shrink: 0; margin-right: 8px;">课程下的章：</label>
            </div>
            <div class="directory">
                <!-- 遍历章节 -->
                <div v-for="chapter in getChaptersByCourseId(form.id)" :key="chapter.chapterId" class="chapter">
                  <div class="chapter-title" @click="toggleChapter(chapter.chapterId)">
                    {{ chapter.title }}
                    <el-button style="flex-shrink: 0;margin-left: 40px" type="danger">Add</el-button>
                    <button @click="confirmDelete(chapter.chapterId)" style="margin-left:70px">X</button>
                    <RouterLink :to="`/backend/chapter-edit/${chapter.chapterId}`">
                    <button style="margin-left:70px">修改</button>
                    </RouterLink>
                  </div>
                  <!-- 展开章节后显示小节 -->
                  <div v-show="expandedChapters.has(chapter.chapterId)" class="sub-chapters">
                    <div v-for="section in getSectionsByChapterId(chapter.chapterId)" :key="section.sectionId" class="sub-chapter">
                      <div class="sub-title" @click="toggleSection(section.sectionId)">
                        {{ section.title }}
                        <button @click="Delete(section.sectionId)" style="margin-left:30px">X</button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
</template>

<style>
.directory {
  width: 300px;
  overflow-y: auto;

  padding: 20px;
}
.chapter-title,
.sub-title {
  padding: 8px;
  cursor: pointer;
  transition: background 0.3s;
}

.chapter-title:hover,
.sub-title:hover {
  background: #f0f0f0;
}
.sub-chapter {
  display: flex;
  margin-left: 16px;
}
</style>
